<template>
    <div class="div-editable"
         @input="changeText"
         @focus="isChange = false"
         @blur="blurFunc"></div>
</template>

<script>
    export default {
        name: 'div_editable',
        props: {
            value: {
                type: String,
                default: ''
            }
        },
        data() {
            return {
                innerText: "",
                isChange: true,
                atCallback: function () {
                    this.remove();
                },
                elCallback: () => {
                    let $el = this.$el;
                    if ($el.innerText === '\n') {
                        $el.innerHTML = ""
                    }
                    this.$emit('input', this.$el.innerHTML);
                    $el.querySelectorAll(".at").forEach(e => {
                        e.addEventListener('DOMSubtreeModified', this.atCallback)
                    })
                },
            }
        },
        watch: {
            value() {
                // console.log("change", this.value, this.isChange, this.isChange || this.value === "");
                if (this.value === "") {
                    // this.innerText = this.value;
                    this.$el.innerHTML = this.value;
                }
            }
        },
        methods: {
            changeText() {
                // this.$emit('input', this.$el.innerHTML);
            },
            blurFunc() {
                this.isChange = true;
                this.$emit('blurFunc')
            }
        },
        mounted() {
            // const config = {characterData: true, subtree: true};
            // const callback = () => {
            //     this.$emit('input', this.$el.innerHTML);
            //     $el.querySelectorAll(".at").forEach(e => {
            //         e.addEventListener('DOMSubtreeModified', function () {
            //             this.remove();
            //         })
            //     })
            // };
            // const observer = new MutationObserver(callback);
            // observer.observe($el, config);

            this.$el.addEventListener('DOMSubtreeModified', this.elCallback, false);
        }
    }
</script>

<style lang="scss">
    .div-editable {
        width: 100%;
        height: 100%;
        overflow-y: auto;
        word-break: break-all;
        outline: none;
        user-select: text;
        white-space: pre-wrap;
        text-align: left;

        -webkit-user-modify: read-write-plaintext-only;

        &:empty:before {
            content: attr(placeholder);
            display: block;
            color: #ccc;
        }

        > span {
            background-color: $theme-light-color;
        }
    }
</style>
